import route from '@/router'

/** menu 转路由 **/
function setRouter(menus){
  let routers = []
  for(let item of menus){
    let r = {
      path: item.url,
      name: item.name,
      component: _import(item.component)
    }
    if(!item.children || item.children .length == 0){
      r.meta = {
        title: item.name,
        keepAlive: item.keepAlive == 1? true: false,
        pageName: item.pageName,
        buttons: item.buttons?item.buttons.split(',') : []
      }
    }else{
      r.children = setRouter(item.children)
    }
    routers.push(r)
  }
  return routers;
}

/** 处理动态import无法加载的问题 **/
function _import(path) {
  return ()=> import(`@/components/${path}.vue`)
}

export default {
  state: {
    menu: [],
    btn: [],
  },
  mutations: {
    SET_MENU:(state,menu)=>{
      state.menu = menu;
    },
    SET_ROUTER:(state,menu)=>{
      let menuRoutes = setRouter(menu)
      route.addRoutes([{
        path: '/home',
        name: '首页',
        component: ()=> import('@/components/page/home/home.vue'),
        children: menuRoutes
      }])
    },
    SET_BUTTONS: (state,btn)=>{
      state.btn = btn;
    }
  }
}
